
package com.bear.cmcc.NetTestHTTP.util;

import com.bear.cmcc.NetTestHTTP.NationalInfoActivity;
import com.bear.cmcc.NetTestHTTP.NetworkTestApp;
import com.bear.cmcc.NetTestHTTP.R;
import com.bear.cmcc.NetTestHTTP.component.ServersConfigBean;
import com.bear.cmcc.NetTestHTTP.component.json.respond.AppUpdateRespond;
import com.bear.cmcc.NetTestHTTP.component.json.respond.ServiceConfigDataRespond;
import com.bear.cmcc.NetTestHTTP.component.json.respond.ServiceConfigRespond;
import com.bear.cmcc.NetTestHTTP.constant.FtpConstant;
import com.bear.cmcc.NetTestHTTP.constant.HttpConstant;
import com.bear.cmcc.NetTestHTTP.constant.HttpTestActivityConstant;
import com.bear.cmcc.NetTestHTTP.constant.MyCommonConstant;
import com.bear.cmcc.NetTestHTTP.constant.NetTestActivityConstant;
import com.bear.cmcc.NetTestHTTP.db.DBCellsHelper;
import com.bear.cmcc.NetTestHTTP.httpUtil.HttpUtil;
import com.bear.cmcc.NetTestHTTP.service.LocalUpdateVillageDBService;
import com.bear.cmcc.NetTestHTTP.service.NetUpdateVersionService;
import com.bear.cmcc.NetTestHTTP.ui.view.LoadingDialog;
import com.bear.net.httpclient.util.MyDes;

import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;

/**
 * 设置界面相关的工具类。
 * 
 * @author suchangjun
 */
public class SetUtil {

    private static final String TAG = "SetUtil";

    /**
     * 下载服务器器配置。
     * 
     * @param coontext
     * @return 下载成功与否。
     */
    public static boolean updateServiceConfig(Context context) {
        File file = new File(context.getFilesDir() + "/"
                + FtpConstant.FtpFileNames.serverListFileName);
        if (file.exists()) {
            file.delete();
        }
        return FtpUtil.downloadFileByComFTP(context, FtpConstant.FtpFileNames.serverListFileName,
                FtpConstant.FtpFileNames.serverListFileName);
    }

    /**
     * 获取服务配置信息
     * 
     * @param context
     * @return List<ServersConfigBean>
     */
    public static List<ServersConfigBean> getServersConfigs(Context context) {
        File file = new File(context.getFilesDir() + "/"
                + FtpConstant.FtpFileNames.serverListFileName);
        List<ServersConfigBean> list = null;
        if (file.exists()) {
            list = JsonUtil.getServersConfigs(context, file);
            return list;
        } else {
            if (updateServiceConfig(context)) {
                list = JsonUtil.getServersConfigs(context, file);
            }
        }
        return list;
    }

    /**
     * 获取服务配置信息
     * 
     * @param context
     * @return List<ServersConfigBean>
     */
    public static ArrayList<ServersConfigBean> getServersConfigsAdapter(Context context) {

        ArrayList<ServersConfigBean> list = NetworkTestApp.getApp().getServiceConfig();
        try {
            if (list == null || list.size() <= 0) {
                if (MyCommonUtil.isNetworkAviable(context)) {
                    ServiceConfigRespond respond = HttpUtil.getServiceConfig(context);
                    if (respond != null && respond.getErrorCode() == HttpConstant.CODE_SUCCESS) {

                        ArrayList<ServiceConfigDataRespond> respondData = respond.getData();
                        if (respondData != null) {
                            ServersConfigBean bean = null;
                            list = new ArrayList<ServersConfigBean>();
                            for (ServiceConfigDataRespond config : respondData) {
                                bean = new ServersConfigBean();
                                bean.setDownloaddictory(config.getDesc());
                                bean.setDownloadName(MyDes.decryptDES(config.getUser(), MyDes.KEY));
                                bean.setDownloadPwd(MyDes.decryptDES(config.getPassword(),
                                        MyDes.KEY));
                                bean.setServerAddress(config.getAddress());
                                bean.setServerPort(config.getPort() + "");
                                bean.setServerName(config.getName());
                                list.add(bean);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    /**
     * 保存选中的服务端配置信息 至客户端
     * 
     * @param b
     */
    public static void setServersConfigBean(ServersConfigBean b, Context context) {
        if (b == null) {
            return;
        }

        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.SERVERS_CONFIG, 0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(ServersConfigBean.JSON_downloaddictory, b.getDownloaddictory());
        editor.putString(ServersConfigBean.JSON_downloadName, b.getDownloadName());
        editor.putString(ServersConfigBean.JSON_downloadPwd, b.getDownloadPwd());
        editor.putString(ServersConfigBean.JSON_ServerAddress, b.getServerAddress());
        editor.putString(ServersConfigBean.JSON_ServerName, b.getServerName());
        editor.putString(ServersConfigBean.JSON_ServerPort, b.getServerPort());
        editor.commit();
    }

    /**
     * 获取客户端保存的服务端名字
     * 
     * @param context
     */
    public static String getServersName(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.SERVERS_CONFIG, 0);
        return preferences.getString(ServersConfigBean.JSON_ServerName, "");
    }

    /**
     * 获取客户端保存的服务端配置信息
     * 
     * @param context
     */
    public static ServersConfigBean getServersConfigBean(Context context) {
        ServersConfigBean b = new ServersConfigBean();
        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.SERVERS_CONFIG, 0);
        if (preferences == null) {
            return null;
        }

        String dictory = preferences.getString(ServersConfigBean.JSON_downloaddictory, "");
        String loadName = preferences.getString(ServersConfigBean.JSON_downloadName, "");
        String loadPwd = preferences.getString(ServersConfigBean.JSON_downloadPwd, "");
        String serverAddress = preferences.getString(ServersConfigBean.JSON_ServerAddress, "");
        String serverName = preferences.getString(ServersConfigBean.JSON_ServerName, "");
        String serverPort = preferences.getString(ServersConfigBean.JSON_ServerPort, "");

        if (loadName.equals("") || loadPwd.equals("") || serverAddress.equals("")
                || serverName.equals("")) {
            dictory = FtpConstant.ComFtp500Config.downDictory500;
            loadName = FtpConstant.ComFtp500Config.userDownload500;
            loadPwd = FtpConstant.ComFtp500Config.passDownload500;
            serverAddress = FtpConstant.ComFtp500Config.host500;
            serverName = FtpConstant.ComFtp500Config.hostname500;
            serverPort = FtpConstant.ComFtp500Config.hostport500;
        }

        b.setDownloaddictory(dictory);
        b.setDownloadName(loadName);
        b.setDownloadPwd(loadPwd);
        b.setServerAddress(serverAddress);
        b.setServerName(serverName);
        b.setServerPort(serverPort);
        return b;
    }

    /**
     * 获取每次下载文件大小。
     * 
     * @param context
     * @param netType {@link MyCommonConstant.NET_TYPE}。
     * @return 大小，单位是kb。
     */
    public static int getEveryDownFileSize(Context context, String netType) {
        try {
            String downFileName = MyCommonUtil.getDownFileName(netType);
            String regEx = "[^0-9]";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(downFileName);
            String fileSize = m.replaceAll("").trim();
            String fileBit = downFileName.substring(fileSize.length(), fileSize.length() + 1);
            int size = Integer.parseInt(fileSize);
            if (fileBit.equals("M")) {
                size = size * 1024;
            }
            return size;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 设置是否执行自动测试。
     * 
     * @param context
     * @param switchValue 开关 true或者false.
     */
    public static void setAutoTest(Context context, boolean switchValue) {
        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.AUTO_TEST, 0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(MyCommonConstant.LocalShareName.AUTO_TEST_SWITCHVALUE, switchValue);
        editor.commit();
    }

    /**
     * 获取是否执行自动测试
     * 
     * @param context
     * @return
     */
    public static boolean getAutoTest(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.AUTO_TEST, 0);
        return preferences.getBoolean(MyCommonConstant.LocalShareName.AUTO_TEST_SWITCHVALUE, true);
    }

    /**
     * 获取自动测试周期。
     * 
     * @param context
     * @return 一个int 的值，单位是分钟。
     * @see #getAutoTestGap(Context)
     */
    public static int getAutoTestGap(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.AUTO_TEST, 10);
        return preferences.getInt(MyCommonConstant.LocalShareName.AUTO_TEST_GAP,
                MyCommonConstant.DEFAULT_AUTO_RUN_GAP);
    }

    /**
     * 获取自动测试周期。
     * 
     * @param context
     * @param gap 一个int 的值，单位是分钟。
     * @return 是否需要更改。
     * @see #setAutoTestGap(Context, int)
     */
    public static boolean setAutoTestGap(Context context, int gap) {
        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.AUTO_TEST, 0);
        // 如果当前的gap不等于已经保存的gap才重新设置一次
        if (getAutoTestGap(context) != gap) {
            SharedPreferences.Editor editor = preferences.edit();
            editor.putInt(MyCommonConstant.LocalShareName.AUTO_TEST_GAP, gap);
            editor.commit();
            return true;
        }
        return false;
    }

    /**
     * 获取自动测试周期。
     * 
     * @param context
     * @return 一个int 的值，单位是分钟。
     * @see #getAutoTestGap(Context)
     */
    public static String getTelNumber(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.TEL_NUMBER, Context.MODE_PRIVATE);
        return preferences.getString(MyCommonConstant.LocalShareName.TEL_NUMBER_VALUE, "");
    }

    /**
     * 设置电话号码。
     * 
     * @param context
     * @param gap 一个int 的值，单位是分钟。
     */
    public static void setTelNumber(Context context, String number) {
        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.TEL_NUMBER, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(MyCommonConstant.LocalShareName.TEL_NUMBER_VALUE, number);
        editor.commit();
    }
    
    

    /**
     * 用来获取是否自动登录。
     * @param context
     * @return
     */
    public static boolean getIsAuToLogin(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.AUTO_LOGIN, Context.MODE_PRIVATE);
        return preferences.getBoolean(MyCommonConstant.LocalShareName.AUTO_LOGIN, false);
    }


    /**
     * 用来设置是否自动登录
     * @param context
     * @param isAutoLogin
     */
    public static void setIsAuToLogin(Context context, boolean isAutoLogin) {
        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.AUTO_LOGIN, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(MyCommonConstant.LocalShareName.AUTO_LOGIN, isAutoLogin);
        editor.commit();
    }

    /**
     * 获取登录的用户名和密码。
     * 
     * @param context
     * @return String[] String[0] 是用户名，String[1] 密码
     */
    public static String[] getLoginInfo(Context context) {
        String[] value = {
                "", ""
        };
        try {
            SharedPreferences preferences = context.getSharedPreferences(
                    MyCommonConstant.LocalShareName.LOGIN, Context.MODE_PRIVATE);
            String name = preferences.getString(MyCommonConstant.LocalShareName.NAME, "");
            String password = preferences.getString(MyCommonConstant.LocalShareName.PASSWORD, "");

            if (TextUtils.isEmpty(name) || TextUtils.isEmpty(password)) {
                return value;
            } else {
                value[0] = MyDes.decryptDES(name, MyDes.LOCAL_KEY);
                value[1] = MyDes.decryptDES(password, MyDes.LOCAL_KEY);
            }
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 保存用户名和密码。
     * 
     * @param context
     * @param name
     * @param password
     */
    public static void setLoginInfo(Context context, String name, String password) {

        if (context == null) {
            return;
        }

        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(password)) {
            return;
        }

        try {
            SharedPreferences preferences = context.getSharedPreferences(
                    MyCommonConstant.LocalShareName.LOGIN, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();

            name = MyDes.encryptDES(name, MyDes.LOCAL_KEY);
            password = MyDes.encryptDES(password, MyDes.LOCAL_KEY);

            editor.putString(MyCommonConstant.LocalShareName.NAME, name);
            editor.putString(MyCommonConstant.LocalShareName.PASSWORD, password);
            editor.commit();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 注销用户名和密码。
     * 
     * @param context
     * @param name
     * @param password
     */
    public static void setLoginInfoLogout(Context context) {

        if (context == null) {
            return;
        }
        NetworkTestApp.getApp().setHaveLogin(false);//用来记录已经登录
        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.LOGIN, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();

        editor.putString(MyCommonConstant.LocalShareName.NAME, "");
        editor.putString(MyCommonConstant.LocalShareName.PASSWORD, "");
        editor.commit();

    }

    /**
     * 导入小区信息到数据库中。
     * 
     * @param context {@link MyCommonConstant.PrivateActionName.NET_WORK_VILLAGE_DATA_DOWN}
     *            导入小区信息的广播名称
     *            {@link MyCommonConstant.PrivateActionName.SERVICE_DOWN_VILLAGE_TYPE}
     *            操作的类型(下载csv：SERVICE_DOWN_VILLAGE_TYPE_CSV,导入数据库：
     *            SERVICE_DOWN_VILLAGE_TYPE_DB)
     *            {@link MyCommonConstant.PrivateActionName.SERVICE_DOWN_VILLAGE_STATUS}
     *            导入小区信息的状态(-1:导入信息出错,0:正在导入中,1:导入完成)
     *            {@link MyCommonConstant.PrivateActionName.SERVICE_DOWN_VILLAGE_CURRENTPRO}
     *            当前操作的进度
     *            {@link MyCommonConstant.PrivateActionName.SERVICE_DOWN_VILLAGE_CURRENTNAME}
     *            当前导入的小区名称
     * @return
     */
    public static void importVillageInfo(Context context) {
        NetworkTestApp.isStop_celldb = false;
        NetworkTestApp.isBackRun_celldb = false;
        Intent intent = new Intent(context, LocalUpdateVillageDBService.class);
        intent.putExtra(LocalUpdateVillageDBService.ISBACKRUN, false);
        context.startService(intent);
    }

    /**
     * 停止当前导入小区信息的过程
     * 
     * @param context
     */
    public static void stopImportVillageInfo(Context context) {
        Intent intentStop = new Intent(context, LocalUpdateVillageDBService.class);
        context.stopService(intentStop);
        NetworkTestApp.isStop_celldb = true;
    }

    /**
     * 根据小区 lac,ci,net,Type获取小区信息。
     * 
     * @param lac 移动网络中 位置区码(LAC)。
     * @param ci 移动网络中 扇区编号。
     * @param netType 值见{@link MyCommonConstant.NET_TYPE}
     * @return
     * @see #importVillageInfo(Context)
     */
    public static String getVillageName(int lac, int ci, String netType, Context context) {
        DBCellsHelper db = null;
        try {
            db = new DBCellsHelper(context);
            String cellName = db.queryCellName(lac, ci, netType);

            return cellName;
        } catch (Exception e) {
            Log.d("SetUtil", "getVillageName Exception:" + e.getMessage());
            return null;
        } finally {
            if (db != null) {
                db.close();
            }
        }
    }

    /**
     * 检查是否需要更新版本(集团)。
     * 
     * @param context
     * @return 是否需要更新。
     * @see #updateNewVersion(Context)
     */
    public static boolean checkShouldUpdateNewVersion(Context context) {
        // 取本地版
        try {
            String[] localVersion = getLocalVersion(context);
            String[] serviceVersion = getServiceVersion(context);
            if (localVersion != null && serviceVersion != null) {
                // 本地的版本号
                String local_versionName = localVersion[1];
                // 服务器的版本号
                String service_versionName = serviceVersion[0];
                if (!local_versionName.equals(service_versionName)) {
                    // 需要更新版本
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (Exception e) {
            Log.d("SetUtil", "checkShouldUpdateNewVersion Exception: " + e.getMessage());
            return false;
        }
    }

    /**
     * 检查是否需要更新版本(福建)。
     * 
     * @param context
     * @return 是否需要更新。
     * @see #updateNewVersion(Context)
     */
    public static boolean checkShouldUpdateNewVersion_FJ(Context context) {
        // 取本地版
        try {
            String[] localVersion = getLocalVersion(context);
            String[] serviceVersion = getServiceVersion_FJ(context);
            if (localVersion != null && serviceVersion != null) {
                // 本地的版本号
                String local_versionName = localVersion[1];
                // 服务器的版本号
                String service_versionName = serviceVersion[0];
                if (!local_versionName.equals(service_versionName)) {
                    // 需要更新版本
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (Exception e) {
            Log.d("SetUtil", "checkShouldUpdateNewVersion Exception: " + e.getMessage());
            return false;
        }
    }

    /**
     * (集团)用来启动下载更新版本的APK的后台服务。 下载完成：会发一个广播
     * {@link MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN}
     * {@link MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN_TYPE}
     * {@link MyCommonConstant.PrivateActionName.NET_WORK_APK_ISUPDATE}
     * {@link MyCommonConstant.PrivateActionName.ALL_APK_DOWNSTATUS}
     * 
     * @param context
     * @see #isNetAPKDataExist(Context)
     */
    public static void startNetDownAPKService(Context context, boolean isDown) {
        if (context != null) {
            if (MyCommonUtil.isServiceRun(context, NetUpdateVersionService.class.getName())) {
                MyCommonUtil.showMessage(context, R.string.new_version_running);
            } else {

                Intent intent = new Intent(context, NetUpdateVersionService.class);
                intent.putExtra(MyCommonConstant.PrivateActionName.SERVICE_DOWNAPK_TYPE,
                        MyCommonConstant.PrivateActionName.SERVICE_DOWNAPK_TYPE_JT);
                intent.putExtra(NetUpdateVersionService.ISDOWN, isDown);
                context.startService(intent);
            }
        }
    }

    /**
     * (福建)用来启动下载更新版本的APK的后台服务。 下载完成：会发一个广播
     * {@link MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN}
     * {@link MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN_TYPE}
     * {@link MyCommonConstant.PrivateActionName.NET_WORK_APK_ISUPDATE}
     * {@link MyCommonConstant.PrivateActionName.ALL_APK_DOWNSTATUS}
     * 
     * @param context
     * @see #isNetAPKDataExist_FJ(Context)
     */
    public static void startNetDownAPKService_FJ(Context context, boolean isDown, String downUrl) {
        if (context != null) {
            Intent intent = new Intent(context, NetUpdateVersionService.class);
            intent.putExtra(MyCommonConstant.PrivateActionName.SERVICE_DOWNAPK_TYPE,
                    MyCommonConstant.PrivateActionName.SERVICE_DOWNAPK_TYPE_FJ);
            intent.putExtra(NetUpdateVersionService.ISDOWN, isDown);
            intent.putExtra(MyCommonConstant.PrivateActionName.ALL_APK_DOWN_URL, downUrl);
            context.startService(intent);
        }
    }

    /**
     * (集团)判断服务端的版本信息在本地是否存在（已下载）
     * 
     * @param context
     * @return
     */
    public static boolean isNetAPKDataExist(Context context) {
        File file = new File(context.getFilesDir() + "/" + FtpConstant.FtpFileNames.apkFileName);
        return file.exists();
    }

    /**
     * (福建)判断服务端的版本信息在本地是否存在（已下载）
     * 
     * @param context
     * @return
     */
    public static boolean isNetAPKDataExist_FJ(Context context) {
        File file = new File(context.getFilesDir() + FtpConstant.FJ_FLOADER
                + FtpConstant.FtpFileNames.apkFileName);
        return file.exists();
    }

    /**
     * 进行更新版本(集团)。 * @param context
     * 
     * @see #checkShouldUpdateNewVersion(Context)
     */
    public static void updateNewVersion(Context context, boolean isDown) {
        startNetDownAPKService(context, isDown);
    }

    /**
     * 进行更新版本(福建)。 * @param context
     * 
     * @see #checkShouldUpdateNewVersion(Context)
     */
    public static void updateNewVersion_FJ(Context context, boolean isDown, String downUrl) {
        startNetDownAPKService_FJ(context, isDown, downUrl);
    }

    /**
     * 安装新的版本（集团）
     * 
     * @param context
     */
    public static void installNewVersion(Context context) {
        // 取下载的APK路径
        Uri uri = Uri.fromFile(new File(context.getFilesDir() + "/"
                + FtpConstant.FtpFileNames.apkFileName));
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    /**
     * 安装新的版本（福建）
     * 
     * @param context
     */
    public static void installNewVersion_FJ(Context context, boolean isFinish) {
        // 取下载的APK路径
        Uri uri = Uri.fromFile(new File(context.getFilesDir() + "/"
                + FtpConstant.FtpFileNames.apkFileName));
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        context.startActivity(intent);
        if (isFinish)
            ((Activity) context).finish();
    }

    /**
     * 获取服务器(集团)版本信息。
     * 
     * @param context
     * @return {version_code,version_name} 例如{"10","version 3.2.19"}。
     */
    public static String[] getServiceVersion(Context context) {
        String remotePath = FtpConstant.FtpFileNames.versionFileName;
        String localPath = FtpConstant.FtpFileNames.versionFileName;// 测试下载一个db文件需要93秒。

        File verfile = new File(context.getFilesDir() + "/" + localPath);
        verfile.delete();

        boolean success = FtpUtil.downloadFileByComFTP(context, localPath, remotePath, false, null,
                true);
        if (success) {
            // 下载配置文件成功
            File file = new File(context.getFilesDir() + "/" + localPath);
            FileReader fr = null;
            BufferedReader buff = null;
            StringBuffer contents = new StringBuffer();
            try {
                if (!file.exists()) {
                    return null;
                }
                fr = new FileReader(file);
                buff = new BufferedReader(fr);
                String text = null;
                while ((text = buff.readLine()) != null) {
                    contents.append(text);
                }
                JSONObject config = new JSONObject(contents.toString());
                String newVersion = config.getString("AppVersion");
                String apkFileName = config.getString("ApkFileName");
                String Description = config.getString("Description");
                return new String[] {
                        newVersion, apkFileName, Description
                };
            } catch (IOException e) {
                Log.d("SetUtil", "getServiceVersion IOException: " + e.getMessage());
                return null;
            } catch (JSONException e) {
                Log.d("SetUtil", "getServiceVersion JSONException: " + e.getMessage());
                return null;
            } catch (Exception e) {
                Log.d("SetUtil", "getServiceVersion Exception: " + e.getMessage());
                return null;
            } finally {
                try {
                    if (fr != null) {
                        fr.close();
                    }
                    if (buff != null) {
                        buff.close();
                    }
                } catch (IOException e) {
                    Log.d("SetUtil",
                            "getServiceVersion finally close IOException: " + e.getMessage());
                }
            }
        } else {
            // 下载配置文件失败
            return null;
        }
    }

    /**
     * 获取服务器(福建)版本信息。
     * 
     * @param context
     * @return {version_code,version_name} 例如{"10","version 3.2.19"}。
     */
    public static AppUpdateRespond getServiceVersion_FJAdapter(Context context) {
        AppUpdateRespond result = HttpUtil.getAppUpdate(context);

        return result;

    }

    /**
     * 获取服务器(福建)版本信息。
     * 
     * @param context
     * @return {version_code,version_name} 例如{"10","version 3.2.19"}。
     */
    public static String[] getServiceVersion_FJ(Context context) {
        String remotePath = FtpConstant.FtpFileNames.versionFileName_FJ;
        String localPath = FtpConstant.FtpFileNames.versionFileName_FJ;
        // //打包需要，使用集团版本号
        // String remotePath = FtpConstant.FtpFileNames.versionFileName;
        // String localPath = FtpConstant.FtpFileNames.versionFileName;

        File verfile = new File(context.getFilesDir() + FtpConstant.FJ_FLOADER + localPath);
        verfile.delete();

        boolean success = FtpUtil.downloadFileByFjFTP(context, new String[] {
            remotePath
        }, true);
        if (success) {
            // 下载配置文件成功
            File file = new File(context.getFilesDir() + FtpConstant.FJ_FLOADER + localPath);
            FileReader fr = null;
            BufferedReader buff = null;
            StringBuffer contents = new StringBuffer();
            try {
                if (!file.exists()) {
                    return null;
                }
                fr = new FileReader(file);
                buff = new BufferedReader(fr);
                String text = null;
                while ((text = buff.readLine()) != null) {
                    contents.append(text);
                }
                JSONObject config = new JSONObject(contents.toString());
                String newVersion = config.getString("AppVersion");
                String apkFileName = config.getString("ApkFileName");
                String Description = config.getString("Description");
                return new String[] {
                        newVersion, apkFileName, Description
                };
            } catch (IOException e) {
                Log.d("SetUtil", "getServiceVersion IOException: " + e.getMessage());
                return null;
            } catch (JSONException e) {
                Log.d("SetUtil", "getServiceVersion JSONException: " + e.getMessage());
                return null;
            } catch (Exception e) {
                Log.d("SetUtil", "getServiceVersion Exception: " + e.getMessage());
                return null;
            } finally {
                try {
                    if (fr != null) {
                        fr.close();
                    }
                    if (buff != null) {
                        buff.close();
                    }
                } catch (IOException e) {
                    Log.d("SetUtil",
                            "getServiceVersion finally close IOException: " + e.getMessage());
                }
            }
        } else {
            // 下载配置文件失败
            return null;
        }
    }

    /**
     * 获取本地版本信息。 String[].length为零，则取本地版本信息出现异常
     * 
     * @param context
     * @return {version_code,version_name} 例如{"10","version 3.2.19"}。
     */
    public static String[] getLocalVersion(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo info = packageManager.getPackageInfo(context.getPackageName(), 0);
            String version_code = String.valueOf(info.versionCode);// 代码版本
            String version_name = info.versionName; // 版本名
            return new String[] {
                    version_code, version_name
            };
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        // return new String[]{"10","version 3.2.19"};
    }

    /**
     * 下载服务端APK文件的状态(集团)
     * 
     * @param context
     * @return -1,下载apk失败，0已是最新版本,1下载成功,进入安装
     */
    public static String getDownServiceAPKStaus(Context context) {
        String[] serverVersion = getServiceVersion(context);
        if (serverVersion.length < 2) {
            return MyCommonConstant.PrivateActionName.ALL_APK_DOWNSTATUS_NO;
        }
        String apkFileName = serverVersion[1];
        File file = new File(context.getFilesDir() + "/" + FtpConstant.FtpFileNames.apkFileName);
        if (file.exists()) {
            file.delete();
        }
        // 下载APK文件
        boolean status = FtpUtil.downloadFileByComFTP(context,
                FtpConstant.FtpFileNames.apkFileName, apkFileName, true);
        if (status) {
            return MyCommonConstant.PrivateActionName.ALL_APK_DOWNSTATUS_YES;
        } else {
            return MyCommonConstant.PrivateActionName.ALL_APK_DOWNSTATUS_NO;
        }
    }

    /**
     * 下载服务端APK文件的状态(集团)
     * 
     * @param context
     * @return -1,下载apk失败，0已是最新版本,1下载成功,进入安装
     */
    public static String getDownServiceAPKStaus_FJ(Context context) {
        String[] serverVersion = getServiceVersion_FJ(context);
        if (serverVersion.length < 2) {
            return MyCommonConstant.PrivateActionName.ALL_APK_DOWNSTATUS_NO;
        }
        String apkFileName = serverVersion[1];
        File file = new File(context.getFilesDir() + "/" + FtpConstant.FtpFileNames.apkFileName);
        if (file.exists()) {
            file.delete();
        }
        // 下载APK文件
        boolean status = FtpUtil.downloadFileByComFTP(context,
                FtpConstant.FtpFileNames.apkFileName, apkFileName, true);
        if (status) {
            return MyCommonConstant.PrivateActionName.ALL_APK_DOWNSTATUS_YES;
        } else {
            return MyCommonConstant.PrivateActionName.ALL_APK_DOWNSTATUS_NO;
        }
    }

    /*
     * @note 从服务器下载新的软件版本到手机内存中
     */
    public static File downloadFile(Context context, String remoteUrl) {

        if (TextUtils.isEmpty(remoteUrl)) {
            return null;
        }
        InputStream is = null;

        // 把从服务器读出的下载流写入到本地临时文件
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        try {
            File savefile = new File(context.getFilesDir() + "/"
                    + FtpConstant.FtpFileNames.apkFileName);
            if (savefile.exists()) {
                savefile.delete();
            }
            Log.i(TAG, "开始下载新版本:" + remoteUrl);
            URL url = new URL(remoteUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            int total = conn.getContentLength();
            conn.setConnectTimeout(5000);
            if (conn.getResponseCode() != HttpStatus.SC_OK) {
                MyCommonUtil.showMessage(context, R.string.error_downLoad_timeout);
                return null;
            }
            is = conn.getInputStream();

            // 把从服务器读出的下载流写入到本地临时文件
            // fos = new FileOutputStream(savefile);

            // 传入的路径必须是files/目录下的文件
            fos = context.openFileOutput(FtpConstant.FtpFileNames.apkFileName,
                    Context.MODE_WORLD_READABLE);

            bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024 * 1024];
            int len;
            int haveDown = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                haveDown = haveDown + len;
                sendDowning(context, (haveDown * 100 / total) + "%", total);
            }
            Log.i(TAG, "下载新版本完成");
            return savefile;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (bis != null) {
                    bis.close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发生下载进度广播.
     * 
     * @param context
     * @param process 百分比
     * @param total 总大小 字节
     */
    public static void sendDowning(Context context, String process, int total) {
        double all = Double.valueOf((total * 100 / (1024 * 1024))) / 100;
        Log.i(TAG, "下载进度 " + process + " 总大小是 " + all + "M");
        Intent intent = new Intent(MyCommonConstant.PrivateActionName.DOWN_PROCESS_ACTION);
        intent.putExtra(MyCommonConstant.PrivateActionName.DOWN_PROCESS, process);
        intent.putExtra(MyCommonConstant.PrivateActionName.DOWN_PROCESS_TOTAL, all + "M");
        context.sendBroadcast(intent);

    }

    /**
     * 打开是否更新版本窗口，并启动下载服务（集团）
     * 
     * @param context
     */
    public static void openIsUpdateVerion(final Context context) {
        Builder b = new AlertDialog.Builder(context).setTitle(context.getString(R.string.tishi))
                .setMessage(context.getString(R.string.isUpdateVersion));
        b.setPositiveButton(context.getString(R.string.cancelUpdate),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Intent intent = new Intent(context, NetUpdateVersionService.class);
                        context.stopService(intent);
                        dialog.dismiss();
                    }
                })
                .setNeutralButton(context.getString(R.string.updateVersion),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                Toast.makeText(context, R.string.downingVersion, Toast.LENGTH_LONG)
                                        .show();
                                updateNewVersion(context, true);

                            }
                        }).create();
        b.show();
    }

    // /**
    // * 打开是否更新版本窗口，并启动下载服务（福建）
    // *
    // * @param context
    // */
    // public static void openIsUpdateVerion_FJ(final Context context) {
    // Builder b = new
    // AlertDialog.Builder(context).setTitle(context.getString(R.string.tishi))
    // .setMessage(context.getString(R.string.isUpdateVersion));
    // b.setPositiveButton(context.getString(R.string.cancelUpdate),
    // new DialogInterface.OnClickListener() {
    // public void onClick(DialogInterface dialog, int whichButton) {
    // Intent intent = new Intent(context, NetUpdateVersionService.class);
    // context.stopService(intent);
    // dialog.dismiss();
    // }
    // })
    // .setNeutralButton(context.getString(R.string.updateVersion),
    // new DialogInterface.OnClickListener() {
    // public void onClick(DialogInterface dialog, int whichButton) {
    // Toast.makeText(context, R.string.downingVersion, Toast.LENGTH_LONG)
    // .show();
    // updateNewVersion_FJ(context, true);
    //
    // }
    // }).create();
    // b.show();
    // }

    /**
     * 打开是否更新版本窗口，并启动下载服务（福建）,取消更新，将关闭activity
     * 
     * @param context
     */
    public static void openIsUpdateVerion_FJ_Close(final Context context, final String message,
            final LoadingDialog loadingDialog, final boolean isExit, final String downUrl,
            boolean isShowShare) {
        Builder b = new AlertDialog.Builder(context).setTitle(
                context.getString(R.string.isUpdateVersion)).setMessage(message);
        b.setPositiveButton(context.getString(R.string.cancel),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Intent intent = new Intent(context, NetUpdateVersionService.class);
                        context.stopService(intent);
                        dialog.dismiss();
                        if (isExit)
                            ((Activity) context).finish();
                    }
                }).setNegativeButton(context.getString(R.string.updateVersion),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Toast.makeText(context, R.string.downingVersion, Toast.LENGTH_LONG).show();
                        updateNewVersion_FJ(context, true, downUrl);
                        if (loadingDialog != null) {
                            loadingDialog.show();
                        }

                    }
                });

        if (isShowShare) {
            b.setNeutralButton(context.getString(R.string.share),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {

                            try {
                                String shareData = context.getString(R.string.down_url) + downUrl;
                                MyCommonUtil.share(context, context.getString(R.string.share),
                                        shareData);
                                dialog.dismiss();
                                if (isExit)
                                    ((Activity) context).finish();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    });
        }

        b.create();
        b.show();
    }

    /**
     * 保存测试页面测试次数
     * 
     * @param times
     */
    public static void setNetTestRuningTimes(int times, Context context) {

        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.NET_TEST_CONFIG, 0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt(
                NetTestActivityConstant.NETTEST_SERVICE_RUNNING_CONFIG.NETTEST_SERVICE_RUNNING_TIMES,
                times);
        editor.commit();
    }

    /**
     * 保存测试页面服务是否关闭状态
     * 
     * @param b
     */
    public static void setNetTestRuningState(boolean state, Context context) {

        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.NET_TEST_CONFIG, 0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(
                NetTestActivityConstant.NETTEST_SERVICE_RUNNING_CONFIG.NETTEST_SERVICE_RUNNING_STATE,
                state);
        editor.commit();
    }

    /**
     * 保存测试页面测试次数
     * 
     * @param times
     */
    public static void setHttpTestRuningTimes(int times, Context context) {

        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.HTTP_TEST_CONFIG, 0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt(
                HttpTestActivityConstant.HTTPTEST_SERVICE_RUNNING_CONFIG.HTTPTEST_SERVICE_RUNNING_TIMES,
                times);
        editor.commit();
    }

    /**
     * 保存测试页面服务是否关闭状态
     * 
     * @param b
     */
    public static void setHttpTestRuningState(boolean state, Context context) {

        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.HTTP_TEST_CONFIG, 0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(
                HttpTestActivityConstant.HTTPTEST_SERVICE_RUNNING_CONFIG.HTTPTEST_SERVICE_RUNNING_STATE,
                state);
        editor.commit();
    }

    /**
     * 获取测试页面测试次数
     * 
     * @param context
     */
    public static int getNetTestRuningTimes(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.NET_TEST_CONFIG, 0);
        return preferences
                .getInt(NetTestActivityConstant.NETTEST_SERVICE_RUNNING_CONFIG.NETTEST_SERVICE_RUNNING_TIMES,
                        0);
    }

    /**
     * 获取测试页面测试服务开启状态
     * 
     * @param context
     */
    public static boolean getNetTestRuningState(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.NET_TEST_CONFIG, 0);
        return preferences
                .getBoolean(
                        NetTestActivityConstant.NETTEST_SERVICE_RUNNING_CONFIG.NETTEST_SERVICE_RUNNING_STATE,
                        false);
    }

    /**
     * 获取Http测试页面测试次数
     * 
     * @param context
     */
    public static int getHttpTestRuningTimes(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.HTTP_TEST_CONFIG, 0);
        return preferences
                .getInt(HttpTestActivityConstant.HTTPTEST_SERVICE_RUNNING_CONFIG.HTTPTEST_SERVICE_RUNNING_TIMES,
                        0);
    }

    /**
     * 获取Http测试页面测试服务开启状态
     * 
     * @param context
     */
    public static boolean getHttpTestRuningState(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(
                MyCommonConstant.LocalShareName.HTTP_TEST_CONFIG, 0);
        return preferences
                .getBoolean(
                        HttpTestActivityConstant.HTTPTEST_SERVICE_RUNNING_CONFIG.HTTPTEST_SERVICE_RUNNING_STATE,
                        false);
    }

}
